package mh.demo.ehcache;

import mh.demo.PrintUtils;
import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;

public class EhcacheDemo01 {
    public static void main(String[] args) {
        run01();
        run02();
    }
    private static void run01() {
        CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder() //（1）
                .withCache("preConfigured",
                        CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10))) // （2）
                .build(); //（3）
        cacheManager.init();  //（4）
        doSomething(cacheManager);
        cacheManager.close();  //（10）
    }

    private static void run02() {
        try (CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()  //（1）
                .withCache("preConfigured", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)))  //（2）
                .build(true)) {  //（3）

            doSomething(cacheManager);

        }
    }

    private static void doSomething(CacheManager cacheManager) {
        Cache<Long, String> preConfigured =
                cacheManager.getCache("preConfigured", Long.class, String.class); //（5）

        Cache<Long, String> myCache = cacheManager.createCache(
                "myCache",
                CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10))
        ); //（6）

        Long key = 1L;
        myCache.put(key, "da one!");  //（7）
        String value = myCache.get(key); //（8）
        PrintUtils.println("key=" + key + ", value=" + value);

        cacheManager.removeCache("preConfigured");  //（9）
    }

}
